package common.util;
import java.util.*;
import java.util.stream.Collectors;

public class ListUtils {

    /**
     * 获取list1中有但是list2中没有的元素。
     */
    public static <T> List<T> difference(List<T> list1, List<T> list2) {
        Set<T> set1 = new HashSet<>(list1);
        Set<T> set2 = new HashSet<>(list2);

        // 计算差集
        set1.removeAll(set2);

        // 如果需要保持原始顺序，请将结果转换回List类型，并且保证输入List支持重复元素
        return list1.stream()
                .filter(set1::contains)
                .collect(Collectors.toList());
    }

    public static void main(String[] args) {
        List<String> list1 = Arrays.asList("apple", "banana", "cherry", "date");
        List<String> list2 = Arrays.asList("banana", "date", "fig");

        List<String> diff = difference(list1, list2);
        System.out.println("Difference: " + diff);  // 输出: Difference: [apple, cherry]

        // 测试反向差集
        List<String> reverseDiff = difference(list2, list1);
        System.out.println("Reverse Difference: " + reverseDiff);  // 输出: Reverse Difference: [fig]
    }
}